<template>
    <div class="question-category-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑分类' : '新增分类' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon><ArrowLeft /></el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form
                    ref="categoryFormRef"
                    :model="formData"
                    :rules="formRules"
                    label-width="120px"
                    class="question-category-form"
                >
                    <!-- 父级分类 -->
                    <el-form-item label="父级分类:" prop="parentId">
                        <el-cascader
                            v-model="formData.parentId"
                            :options="parentCategoryOptions"
                            :props="{ 
                                checkStrictly: true, 
                                emitPath: false,
                                value: 'value',
                                label: 'label',
                                children: 'children'
                            }"
                            placeholder="请选择父级分类（不选择默认为第一级）"
                            clearable
                            @change="handleParentCategoryChange"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 分类名称 -->
                    <el-form-item label="分类名称:" prop="categoryName">
                        <el-input
                            v-model="formData.categoryName"
                            placeholder="输入分类名称"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 语言 -->
                    <el-form-item label="语言:" prop="language">
                        <el-select v-model="formData.language" placeholder="请选择语言" style="width: 200px">
                            <el-option label="中文" value="zh-CN" />
                            <el-option label="英文" value="en-US" />
                        </el-select>
                    </el-form-item>

                    <!-- 是否显示 -->
                    <el-form-item label="是否显示:" prop="isVisible">
                        <el-select v-model="formData.isVisible" placeholder="请选择" style="width: 200px">
                            <el-option label="显示" :value="1" />
                            <el-option label="隐藏" :value="0" />
                        </el-select>
                    </el-form-item>

                    <!-- 分类图标 -->
                    <el-form-item label="分类图标:" prop="icon">
                        <el-input
                            v-model="formData.icon"
                            placeholder="输入图标名称"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 分类描述 -->
                    <el-form-item label="分类描述:" prop="description">
                        <el-input
                            v-model="formData.description"
                            type="textarea"
                            :rows="4"
                            placeholder="请输入分类描述"
                            style="width: 500px"
                        />
                    </el-form-item>

                    <!-- 分类层级（只读显示） -->
                    <!-- <el-form-item label="分类层级:" v-if="!isEdit">
                        <el-input
                            :value="`第 ${formData.level} 级`"
                            readonly
                            style="width: 200px"
                        />
                    </el-form-item> -->

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <div class="form-actions">
                            <el-button @click="handleCancel">取消</el-button>
                            <el-button type="primary" @click="handleSubmit">保存</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import { ServiceCategory } from '@/types/serviceCategory';
import { createServiceCategory, updateServiceCategory, getServiceCategoryById, getServiceCategoryTree } from '@/api/system/serviceCategory';

const route = useRoute();
const router = useRouter();

const id = route.params.id as string;
const isEdit = computed(() => !!id);

// 表单引用
const categoryFormRef = ref();

// 父级分类选项
const parentCategoryOptions = ref<any[]>([]);

// 表单数据
const formData = reactive({
    parentId: '',
    level: 1,
    icon: '',
    isVisible: 1,
    language: 'zh-CN',
    categoryName: '',
    description: ''
});

// 分类树数据（用于查找父级level）
const categoryTreeData = ref<ServiceCategory[]>([]);

// 表单验证规则
const formRules = {
    categoryName: [
        { required: true, message: '分类名称不能为空', trigger: 'blur' },
        { min: 1, max: 100, message: '分类名称长度在1-100个字符', trigger: 'blur' }
    ],
    description: [
        { max: 500, message: '描述长度不能超过500个字符', trigger: 'blur' }
    ],
    language: [
        { required: true, message: '请选择语言', trigger: 'change' }
    ],
    isVisible: [
        { required: true, message: '请选择是否显示', trigger: 'change' }
    ]
};

// 提交表单
const handleSubmit = async () => {
    if (!categoryFormRef.value) return;
    
    try {
        await categoryFormRef.value.validate();
        
        const categoryData = {
            parentId: formData.parentId || null,
            level: formData.level,
            icon: formData.icon,
            isVisible: formData.isVisible,
            language: formData.language,
            categoryName: formData.categoryName,
            description: formData.description
        };

        if (isEdit.value) {
            // 编辑模式
            const res = await updateServiceCategory(id, categoryData);
            const responseData = res as any;
            
            if (responseData && responseData.code === 200) {
                ElMessage.success('更新成功');
                router.push('/question-category-list');
            } else {
                const errorMsg = (responseData && responseData.msg) || '更新失败';
                ElMessage.error(errorMsg);
            }
        } else {
            // 新增模式
            const res = await createServiceCategory(categoryData);
            const responseData = res as any;
            
            if (responseData && responseData.code === 200) {
                ElMessage.success('创建成功');
                router.push('/question-category-list');
            } else {
                const errorMsg = (responseData && responseData.msg) || '创建失败';
                ElMessage.error(errorMsg);
            }
        }
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('操作失败，请稍后重试');
    }
};

// 取消操作
const handleCancel = () => {
    router.push('/question-category-list');
};

// 页面初始化
onMounted(async () => {
    // 加载父级分类选项
    await loadParentCategoryOptions();
    
    if (isEdit.value) {
        // 编辑模式：加载现有数据
        await loadCategoryData(id);
    }
});

// 父级分类选择变化处理
const handleParentCategoryChange = (value: string) => {
    if (value) {
        // 选择了父级分类，查找父级的level
        const parentLevel = findParentLevel(categoryTreeData.value, value);
        formData.level = parentLevel + 1;
        console.log(`选择父级分类 ${value}，父级level: ${parentLevel}，当前level: ${formData.level}`);
    } else {
        // 没有选择父级分类，默认为第一级
        formData.level = 1;
        console.log('未选择父级分类，当前level: 1');
    }
};

// 在分类树中查找指定ID的分类level
const findParentLevel = (categories: ServiceCategory[], targetId: string): number => {
    for (const category of categories) {
        if (category.id === targetId) {
            return category.level;
        }
        if (category.children && category.children.length > 0) {
            const result = findParentLevel(category.children, targetId);
            if (result !== -1) {
                return result;
            }
        }
    }
    return -1; // 未找到
};

// 加载父级分类选项
const loadParentCategoryOptions = async () => {
    try {
        const res = await getServiceCategoryTree();
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            // 保存原始分类树数据
            categoryTreeData.value = responseData.data;
            const transformedOptions = transformToCascaderOptions(responseData.data);
            parentCategoryOptions.value = transformedOptions;
            console.log('父级分类选项:', transformedOptions);
        } else {
            console.error('获取父级分类选项失败:', responseData);
            ElMessage.error('获取父级分类选项失败');
        }
    } catch (error) {
        console.error('获取父级分类选项失败:', error);
        ElMessage.error('获取父级分类选项失败');
    }
};

// 转换分类树为级联选择器选项
const transformToCascaderOptions = (categories: ServiceCategory[]): any[] => {
    console.log('转换分类数据:', categories);
    const result = categories.map(category => {
        const option = {
            value: category.id,
            label: category.categoryName,
            children: category.children && category.children.length > 0 
                ? transformToCascaderOptions(category.children) 
                : undefined
        };
        console.log('转换后的选项:', option);
        return option;
    });
    console.log('最终转换结果:', result);
    return result;
};

// 加载分类数据
const loadCategoryData = async (categoryId: string) => {
    try {
        const res = await getServiceCategoryById(categoryId);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            const data = responseData.data;
            formData.parentId = data.parentId || '';
            formData.level = data.level || 1;
            formData.icon = data.icon || '';
            formData.isVisible = data.isVisible;
            formData.language = data.language || 'zh-CN';
            formData.categoryName = data.categoryName || '';
            formData.description = data.description || '';
            
            console.log('编辑模式加载数据:', {
                parentId: formData.parentId,
                level: formData.level,
                categoryName: formData.categoryName
            });
        } else {
            const errorMsg = (responseData && responseData.msg) || '获取分类详情失败';
            ElMessage.error(errorMsg);
        }
    } catch (error) {
        console.error('获取分类详情失败:', error);
        ElMessage.error('获取分类详情失败，请稍后重试');
    }
};
</script>

<style scoped>
.question-category-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.page-header {
    border-radius: 8px;
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #333;
    font-size: 24px;
}

.form-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-card {
    border-radius: 8px;
}

.question-category-form {
    padding: 30px;
}

.form-hint {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 4px;
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .question-category-form-container {
        padding: 10px;
    }
    
    .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
    }
    
    .question-category-form {
        padding: 20px;
    }
    
    .form-actions {
        justify-content: center;
    }
}
</style>
